import {view, View, binder} from "adajs";
import ReadingService from "./state.js";
import {importScript} from "../../lib/helper";
import User from "../../lib/user";

@view({
    className: "reading",
    template: "./template.html",
    style: "./style.scss",
    dataset: {
        service: ReadingService
    }
})
class Reading extends View {
    onready() {
        let tex = this.getCurrentState().info;
        if (tex) {
            importScript("/static/baidu_tts_cors.js").then(() => {
                this.context.request.get("/api/lgb/app/lgb/getAccessToken").then(info => {
                    btts({
                        tex,
                        tok: info.msg,
                        cuid: User.getUserInfo().id,
                        ctp: 1,
                        lan: 'zh'
                    }, {
                        volume: 0.3,
                        autoDestory: false,
                        timeout: 10000,
                        hidden: false,
                        onInit: (htmlAudioElement) => {
                        },
                        onSuccess: (htmlAudioElement) => {
                            this.commit("result", {result: true, msg: ""}).then(() => {
                                this.finder("box").getElement().appendChild(htmlAudioElement);
                            });
                        },
                        onError: (errorText) => {
                            this.commit("result", {result: false, msg: errorText});
                        },
                        onTimeout: () => {
                            this.commit("result", {result: false, msg: "超时请重试"}).then(() => {
                                setTimeout(() => {
                                    this.close();
                                }, 2000);
                            });
                        }
                    });
                });
            });
        } else {
            this.commit("result", {result: false, msg: "没有需要转换的文字，请重试"}).then(() => {
                setTimeout(() => {
                    this.close();
                }, 2000);
            });
        }
    }

    @binder("close")
    close() {
        this.getParent().removeChild(this);
    }
}

export default Reading;